# RequestHandlers for the web interface.

import Cookie
from datetime import datetime
import logging
import os
import time

import webapp2

#from google.appengine.api import memcache
from google.appengine.api import users
#from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import auth
from models import *

class IndexHandler(webapp2.RequestHandler):
  def get(self):
    path = os.path.join(os.path.dirname(__file__), 'html/index.html')
    authenticated = auth.current_user(self.request)

    values = {
      'authenticated': authenticated,
    }
    self.response.out.write(template.render(path, values))

class PersonJoinHandler(webapp2.RequestHandler):
  def get(self):
    path = os.path.join(os.path.dirname(__file__), 'html/join.html')
    error = self.request.get('error')
    values = {
      'error': error,
    }
    self.response.out.write(template.render(path, values))
    
  def post(self):
    email = self.request.get('email')
    name = self.request.get('name')
    if not email:
      self.response.set_status(500)
      self.response.out.write('No email returned')
      return
      
    # Check if there is an existing person created already.
    existing = Person.all().filter('emails =', email).get()
    if existing:
      existing.name = name
      if users.get_current_user():
        existing.google_user = users.get_current_user()
      existing.put()
    else:
      new_person = Person(name=name, email=[email])
      if users.get_current_user():
        new_person.google_user = users.get_current_user()
      new_person.put()
      
    auth.set_current_user(self.response, email)
    self.redirect('/')
    
class AddExpenseHandler(webapp2.RequestHandler):
  def get(self):
    path = os.path.join(os.path.dirname(__file__), 'html/add.html')
    error = self.request.get('error')
    values = {
      'error': error,
    }
    self.response.out.write(template.render(path, values))

  def post(self):
    description = self.request.get('description')
    amount = self.request.get('amount')
    creditor_email = self.request.get('creditor')
    debitor_emails = self.request.get('debitors')
    location = self.request.get('location')
    # TODO: How to specify percentages?
    # TODO: store expense.
    self.redirect('/add')
  
